Taro: 不能import第三方库

Created on 16 Aug 2018  ·  7Comments  ·  Source: NervJS/taro

问题描述
import第三方库会得到undefined

复现步骤
[复现问题的步骤]

  1. 安装一个dayjs
yarn add -s dayjs
  1. import dayjs
import dayjs from 'dayjs'
  1. 打印dayjs
console.log(dayjs)
// 控制台输出 undefined

期望行为
正常使用import

报错信息

如果直接使用的话报错:

VM7355:1 thirdScriptError
dayjs_min_js_1.default is not a function;at App lifeCycleMethod onLaunch function
TypeError: dayjs_min_js_1.default is not a function
at _App.componentDidMount (http://127.0.0.1:53714/appservice/app.js:35:47)
at t.onLaunch (http://127.0.0.1:53714/appservice/npm/@tarojs/taro-weapp/dist/index.js:2609:13)
at t (http://127.0.0.1:53714/appservice/__dev__/WAService.js:18:25054)
at new t (http://127.0.0.1:53714/appservice/__dev__/WAService.js:18:26437)
at Function. (http://127.0.0.1:53714/appservice/__dev__/WAService.js:18:26622)
at http://127.0.0.1:53714/appservice/__dev__/WAService.js:18:9835
at http://127.0.0.1:53714/appservice/app.js:55:1
at require (http://127.0.0.1:53714/appservice/__dev__/WAService.js:19:20075)
at http://127.0.0.1:53714/appservice/appservice?t=1534412768581:1027:9

系统信息

  • 操作系统: [macOS]
  • Taro 版本 [1.0.0-beta.10 typescript模版]
  • Node.js 版本 [v10.6.0]

补充信息

const dayjs = require('dayjs')

这样是可以的

Most helpful comment

import moment from 'moment';

在 TypeScript 实际上会被编译成 const moment = require('moment').default;,你可以通过调整 tsconfigallowSyntheticDefaultImports 来调整默认 import 的值。

ref:
https://github.com/Microsoft/TypeScript/issues/5565

All 7 comments

import * as dayjs from 'dayjs'

这样可以吗

我用的moment

import moment from 'moment';

这样是可以的
image

import moment from 'moment';

在 TypeScript 实际上会被编译成 const moment = require('moment').default;,你可以通过调整 tsconfigallowSyntheticDefaultImports 来调整默认 import 的值。

ref:
https://github.com/Microsoft/TypeScript/issues/5565

import * as moment from 'moment';

我发现有些第三方库可以正确import,显示错误 module "xxx" is not defined

@yuche 改了allowSyntheticDefaultImports不行,import * as 这样可以,就这么用吧

今天升级到了 1.1.0,发现在运行时提示 moment is not defined,
此时的 import * as moment from 'moment';不能正常使用,
根据 https://momentjs.com/docs/#/use-it/typescript/, 在 tsconfig.json 添加 "allowSyntheticDefaultImports": true, 然后使用 import moment from 'moment';, 可以正常使用

Was this page helpful?
0 / 5 - 0 ratings

Related issues

luckyadam picture luckyadam  ·  167Comments

awesomepan picture awesomepan  ·  26Comments

luankefei picture luankefei  ·  30Comments

luckyadam picture luckyadam  ·  55Comments

Chen-jj picture Chen-jj  ·  40Comments